package com.hope.bubble.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hope.bubble.common.api.ApiResult;
import com.hope.bubble.model.dto.CreateTopicDTO;
import com.hope.bubble.model.entity.BubblePost;
import com.hope.bubble.model.entity.UmsUser;
import com.hope.bubble.model.vo.PostVO;
import com.hope.bubble.service.IBubblePostService;
import com.hope.bubble.service.IUmsUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

import static com.hope.bubble.jwt.JwtUtil.USER_NAME;

/**
 * 文件名：BubblePostController
 * 创建者：hope
 * 邮箱：1602774287@qq.com
 * 微信：hope4cc
 * 创建时间：2022/10/22-10:13
 * 描述：
 */
@RestController
@RequestMapping("/post")
public class BubblePostController extends BaseController {
    @Resource
    private IBubblePostService BubblePostService;

    @Resource
    private IUmsUserService umsUserService;


    /**
     *
     * @param tab 最新还是最热的帖子
     * @param pageNo 当前第几页
     * @param pageSize 每页多少条
     * @return
     */
    @GetMapping("/list")
    public ApiResult<Page<PostVO>> list(@RequestParam(value = "tab", defaultValue = "latest") String tab,
                                        @RequestParam(value = "pageNo", defaultValue = "1")  Integer pageNo,
                                        @RequestParam(value = "size", defaultValue = "10") Integer pageSize) {
        Page<PostVO> list = BubblePostService.getList(new Page<>(pageNo, pageSize), tab);
        return ApiResult.success(list);
    }


    /**
     *
     * @param userName token的用户名dUSER_NAME   userName从token中解析出来的用户名
     * @param dto 前端传过来的信息 一一对应
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public ApiResult<BubblePost> create(@RequestHeader(value = USER_NAME) String userName
            , @RequestBody CreateTopicDTO dto) {
        //数据库查找用户名
        UmsUser user = umsUserService.getUserByUsername(userName);
        //dto 代表前端请求的代表用户的帖子信息对象，和当前对应的发贴人 传给create
        BubblePost topic = BubblePostService.create(dto, user);
        return ApiResult.success(topic);
    }


    /**
     *
     * @param id 帖子的id 是个字符串
     * @return
     */
    @GetMapping()
    public ApiResult<Map<String, Object>> view(@RequestParam("id") String id) {
        //调用业务层BubblePostService得到帖子的详情
        Map<String, Object> map = BubblePostService.viewTopic(id);
        return ApiResult.success(map);
    }
}